package cn.daniellee.plugin.rs.storage;

import cn.daniellee.plugin.rs.RestrictedShop;
import cn.daniellee.plugin.rs.model.PlayerData;
import com.google.gson.Gson;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StorageConverter {

	private final SqliteStorage sqliteStorage;

	private final MysqlStorage mysqlStorage;

	public StorageConverter(SqliteStorage sqliteStorage, MysqlStorage mysqlStorage) {
		this.sqliteStorage = sqliteStorage;
		this.mysqlStorage = mysqlStorage;
	}

	// 只拷贝老玩家数据，欢迎数据丢弃（老玩家不会再被欢迎）
	public void execute() {
		String tablePrefix = RestrictedShop.getInstance().getConfig().getString("storage.mysql.table-prefix", "rs_");
		Connection sqliteConn = sqliteStorage.getConnection();
		Connection mysqlConn = mysqlStorage.getConnection();
		// 查询所有玩家
		List<PlayerData> allPlayer = new ArrayList<>();
		String playerQuery = "SELECT `name`,`shop`,`check_sum`,`index_list`,`purchase_numbers`,`sold_numbers`,`percentage`,`generate_at` FROM `player`";
		try(Statement statement = sqliteConn.createStatement()){
			ResultSet resultSet = statement.executeQuery(playerQuery);
			while (resultSet.next()) {
				PlayerData playerData = new PlayerData();
				playerData.setName(resultSet.getString("name"));
				playerData.setShop(resultSet.getString("shop"));
				playerData.setCheckSum(resultSet.getString("check_sum"));
				playerData.setIndexList(new Gson().fromJson(resultSet.getString("index_list"), Integer[].class));
				playerData.setPurchaseNumbers(new Gson().fromJson(resultSet.getString("purchase_numbers"), Integer[].class));
				playerData.setSoldNumbers(new Gson().fromJson(resultSet.getString("sold_numbers"), Integer[].class));
				playerData.setPercentage(resultSet.getInt("percentage"));
				playerData.setGenerateAt(resultSet.getLong("generate_at"));
				allPlayer.add(playerData);
			}
		} catch (SQLException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while trans Sqlite data to Mysql.");
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
		}
		// 写入MySQL
		String playerInsert = "INSERT INTO `" + tablePrefix + "player` (`name`,`shop`,`check_sum`,`index_list`,`purchase_numbers`,`sold_numbers`,`percentage`,`generate_at`) VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `check_sum` = ?,`index_list` = ?,`purchase_numbers` = ?,`sold_numbers` = ?,`percentage` = ?,`generate_at` = ?;";
		PreparedStatement statement = null;
		try {
			// 关闭MySQL自动提交
			mysqlConn.setAutoCommit(false);
			statement = mysqlConn.prepareStatement(playerInsert);
			for (PlayerData playerData : allPlayer) {
				statement.clearBatch();
				statement.setString(1, playerData.getName());
				statement.setString(2, playerData.getShop());
				statement.setString(3, playerData.getCheckSum());
				String indexList = new Gson().toJson(playerData.getIndexList());
				statement.setString(4, indexList);
				String purchaseNumbers = new Gson().toJson(playerData.getPurchaseNumbers());
				statement.setString(5, purchaseNumbers);
				String soldNumbers = new Gson().toJson(playerData.getSoldNumbers());
				statement.setString(6, soldNumbers);
				statement.setInt(7, playerData.getPercentage());
				statement.setLong(8, playerData.getGenerateAt());
				statement.setString(9, playerData.getCheckSum());
				statement.setString(10, indexList);
				statement.setString(11, purchaseNumbers);
				statement.setString(12, soldNumbers);
				statement.setInt(13, playerData.getPercentage());
				statement.setLong(14, playerData.getGenerateAt());
				statement.addBatch();
			}
			statement.executeBatch();
			mysqlConn.commit();
		} catch (SQLException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while trans Sqlite data to Mysql.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
		} finally {
			try {
				mysqlConn.setAutoCommit(true);
				if (statement != null) {
					statement.close();
				}
			} catch (SQLException ignored) {}
		}
	}
}
